<!-- AI模板 -->
<template>
  <div class="dashboard-editor-container">
    <div class="xxx" style="margin-top: 10px;">
      <div style="display:flex;justify-content:space-between;">
        <!-- <partitionTree :nodeData="nodeData" :addTemplate="false" @handleNodeClick="handleNodeClick" :defaultExpandAll="false" :expandArray="expandArray" ref="partitionTree" @toggleVisibility="toggleVisibility"></partitionTree> -->
        <div :style="{ width:'100%'}"  class="box" style="background:#fff;padding:20px;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <!-- <el-button type="primary" @click="addModer">注册资产</el-button> -->
          <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px" height="640">
            <el-table-column label="序号" width="80" type="index" :index='(index) => { return (index + 1) + (pageNum - 1) * pageSize }'> </el-table-column>
            <!-- <el-table-column label="所在分区" prop="Department" width="80" align="left" show-overflow-tooltip></el-table-column> -->
            <!-- <el-table-column label="所在分区" prop="PrimArea" width="150" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.PrimArea }} / {{ row.SecondArea }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所在校区" prop="SchoolName"  align="left" show-overflow-tooltip></el-table-column> -->
            <el-table-column label="所在教室" prop="ClassName" width="100" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="资产备注" prop="UseName" width="100" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="联系电话" prop="Phone" width="120" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作系统" prop="DeviceClass"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="资产类型" prop="DeviceType"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="硬件标识" prop="HardID"  align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="注册时间" prop="CreateTime" width="160px" align="left" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="220px" align="left" fixed="right" >
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="changeModer(scope.row)">注册</el-button>
                <el-button size="mini" type="danger" @click="deleteModer(scope.row)">删除</el-button>
                <el-button size="mini" type="success" @click="detailsChange(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" 
            :current-page=pageNum
            :page-size=pageSize
            background 
            layout="total, prev, pager, sizes, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 分区弹窗 -->
    <el-dialog 
      top="5vh"
      :close-on-click-modal="false" 
      :close-on-press-escape="false" 
      :visible.sync="moderVisible"
      :title="Action === 1 ? '添加资产' : '资产注册'" 
      v-el-drag-dialog @close="Moder = {}" width="1000px">
      <el-row>
      <el-form label-width="120px" :rules="rules" :model="Moder" ref="Moder">
        <!-- <el-form-item label="所在分区" prop="PrimArea">
          <el-cascader
            disabled
            ref="cascaderAddr"
            style="width:100%;"
            v-model="Moder.PrimArea"
            placeholder="请选择分区"
            clearable
            :options="nodeData"
            :props="{ expandTrigger: 'hover', label: 'Name', value: 'Name', children:'Children'}"
            @change="handleChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="校区编码" prop="SchoolID">
          <el-input placeholder="请输入校区编码" maxlength="16" :disabled="Action === 2" v-model="Moder.SchoolID"></el-input>
        </el-form-item>
        <el-form-item label="校区名称" prop="SchoolName">
          <el-input placeholder="请输入校区名称" maxlength="16" :disabled="Action === 2" v-model="Moder.SchoolName"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="资产编码" prop="DeviceID">
          <el-input placeholder="请输入资产编码" maxlength="16" v-model="Moder.DeviceID"></el-input>
        </el-form-item> -->
        <el-col :span="12">
          <el-form-item label="资产名称" prop="DeviceName">
            <el-input placeholder="请输入资产名称" maxlength="32" v-model.trim="Moder.DeviceName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产编码" prop="DeviceID">
            <el-input placeholder="请输入资产编码" maxlength="32" v-model.trim="Moder.DeviceID"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="使用者角色:" prop="Role">
            <el-select v-model="Moder.Role" placeholder="请选择部门" style="width:100%">
              <el-option v-for="(item, index) in RoleList" :key="index" :label="item.Role" :value="item.Role"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始使用日期:" prop="StartDate">
            <el-date-picker
              style="width:100%"
              v-model="Moder.StartDate"
              type="date"
              format="yyyy 年 MM 月 dd 日"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教室" prop="ClassName">
            <el-input placeholder="请输入教室" maxlength="32" v-model.trim="Moder.ClassName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="Department">
            <el-select v-model="Moder.Department" placeholder="请选择部门" style="width:100%">
              <el-option v-for="(item, index) in DepartmentList" :key="index" :label="item.DepartmentName" :value="item.DepartmentName"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产备注" prop="UseName">
            <el-input placeholder="请输入资产备注" maxlength="16" v-model.trim="Moder.UseName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="Phone">
            <el-input placeholder="请输入联系电话" oninput ="value=value.replace(/[^0-9-]/g,'')" v-model="Moder.Phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作系统" prop="DeviceClass">
            <el-select v-model="Moder.DeviceClass" placeholder="请选择操作系统" style="width:100%">
              <el-option  label="Windows" value="Windows"></el-option>
              <el-option  label="Mac" value="Mac"></el-option>
              <el-option  label="Android" value="Android"></el-option>
              <el-option  label="Linux" value="Linux"></el-option>
              <el-option  label="Other" value="Other"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产类型" prop="DeviceType">
            <el-select v-model="Moder.DeviceType" placeholder="请选择资产类型" style="width:100%">
              <el-option  label="品牌机" value="品牌机"></el-option>
              <el-option  label="组装机" value="组装机"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="硬件标识" prop="HardID">
            <el-input placeholder="请输入硬件标识" maxlength="16" :disabled="Action === 2" v-model="Moder.HardID"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="资产描述" prop="Descp">
            <el-input placeholder="请输入资产描述" type="textarea" :rows="3" v-model="Moder.Descp"></el-input>
          </el-form-item>
        </el-col>
      </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer" v-show="Action !== 4">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="moderVisible = false, reSource = [], $set(reSource, 'isSelected', false)">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog v-el-drag-dialog title="资产详情" :close-on-click-modal="false" :visible.sync="dialogTableVisible"  width="70%">
      <div>
        <el-row>
          <el-descriptions title="资产基本信息" class="margin-top" :column="3"  border>
            <!-- <el-descriptions-item label="所在分区">{{ Moder.PrimArea }}/{{ Moder.SecondArea }}</el-descriptions-item>
            <el-descriptions-item label="校区名称">{{ Moder.SchoolName }}</el-descriptions-item>
            <el-descriptions-item label="校区编码">{{ Moder.SchoolID }}</el-descriptions-item> -->
            <el-descriptions-item label="资产名称">{{ Moder.DeviceName }}</el-descriptions-item>
            <el-descriptions-item label="资产编码">{{ Moder.DeviceID }}</el-descriptions-item>
            <el-descriptions-item label="资产IP">{{ Moder.DeviceIP }}</el-descriptions-item>
            <el-descriptions-item label="所在教室">{{ Moder.ClassName }}</el-descriptions-item>
            <!-- <el-descriptions-item label="资产备注">{{ Moder.UseName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ Moder.Phone }}</el-descriptions-item> -->
            <el-descriptions-item label="操作系统">{{ Moder.DeviceClass }}</el-descriptions-item>
            <el-descriptions-item label="资产类型">{{ Moder.DeviceType }}</el-descriptions-item>
            <el-descriptions-item label="硬件标识">{{ Moder.HardID }}</el-descriptions-item>
            <el-descriptions-item label="所属部门">{{ Moder.Department }}</el-descriptions-item>
            <el-descriptions-item label="电脑名称">{{ Moder.ComputerName }}</el-descriptions-item>
            <el-descriptions-item label="电脑系统">{{ Moder.OsInfo }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ Moder.CreateTime }}</el-descriptions-item> 
          </el-descriptions>
        </el-row>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogTableVisible = false;">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import { connrequest } from '@/api/firstPage'
import { parseTime, getuuid, recursiveGetNodePath, recursiveGetChildNodePath } from '@/utils/index'
import elDragDialog from "@/directive/el-drag-dialog"; 
import partitionTree from "@/components/partitionTree"; 
export default {
  directives: { elDragDialog },
  components: {
    partitionTree,
    connsearch
  },
  data() {
    let that = this
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      containerWidth: 'calc(100% - 240px)',
      tableData: [],
      nodeData: [],
      RoleList: [],
      Action: 1,
      Moder: {},
      moderVisible: false,
      dialogTableVisible: false,
      reSource: [],
      partitionList: [],
      expandArray: [],
      DepartmentList: [],
      choseArea: {},
      searchform: {},
      rules:{
        SchoolID: [
          {required: true, message: '请选择校区编码', trigger: 'blur'}
        ],
        SchoolName: [
          {required: true, message: '请选择校区名称', trigger: 'blur'}
        ],
        Role: [
          {required: true, message: '请选择使用者角色', trigger: 'change'}
        ],
        PrimArea: [
          {required: true, message: '请选择上级分区', trigger: 'change'}
        ],
        SecondArea: [
          {required: true, message: '请输入分区名称', trigger: 'blur'}
        ],
        AreaCode: [
          {required: true, message: '请输入分区编码', trigger: 'blur'}
        ],
        ClassName: [
          {required: true, message: '请输入教室', trigger: 'blur'}
        ],
        Phone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          // {
          //   validator: function(rule, value, callback) {
          //     if (/[^0-9-]/.test(value)) {
          //       callback(new Error("手机号格式错误"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: "blur"
          // }
        ],
        Department: [
          {required: true, message: '请选择部门', trigger: 'change'}
        ],
        DeviceClass: [
          {required: true, message: '请选择操作系统', trigger: 'change'}
        ],
        DeviceType: [
          {required: true, message: '请选择资产类型', trigger: 'change'}
        ],
        StartDate: [
          {required: true, message: '请选择开始使用日期', trigger: 'change'}
        ],
        DeviceID: [
          {required: true, message: '请选择资产编码', trigger: 'blur'}
        ],
        DeviceName: [
          {required: true, message: '请输入资产名称', trigger: 'blur'}
        ],
      },
      formOptions: [
        {
          col: 7,
          label: "资产名称", // label文字
          prop: "DeviceName", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入资产名称,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceName = val
            },
          },
        },
        {
          col: 7,
          label: "资产编码", // label文字
          prop: "DeviceID", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入资产编码,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceID = val
            },
          },
        },
        {
          col: 7,
          label: "MAC地址", // label文字
          prop: "DeviceMAC", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入MAC地址,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceMAC = val
            },
          },
        },
      ],
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    this.getData()
    this.GetDepartment()
    this.GetParamDictRole()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    async GetParamDictRole(){
      const res = await connrequest('GetParamDictRole')
      this.RoleList = res.Data
    },
    async GetDepartment(){
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    async getData() {
      const res = await connrequest('GetUnknownDeviceSumTree')
      let partitionList = []
      let expandArray = []
      res.Data.PrimName = res.Data.RootName //因为后端返回的所有分区名字叫RootName，子菜单又叫PrimAreaName, 这里做个转换
      this.RootName = res.Data.RootName
      res.Data.disabled = true
      res.Data.edit = false
      res.Data.PrimArea.map(item => {
        item.edit = false
        partitionList.push(item)
        expandArray.push(res.Data.RootName, item.PrimAreaName)
      })
      this.nodeData = [this.transformData(res.Data)]
      this.partitionList = partitionList
      this.expandArray = expandArray
      this.GetDictArea(this.choseArea)
    },
    transformData(inputData) {
      const { RootName, OffLineCount, OnlineCount, PrimArea} = inputData;
        return {
          Name: RootName,
          level: 1,
          Count: OffLineCount + OnlineCount,
          Children: PrimArea.map(area => ({
            Name: area.PrimAreaName,
            Count: area.OffLineCount + area.OnlineCount,
            level: 2,
            Children: area.SecondArea.map(secondArea => ({
              Name: secondArea.SecondAreaName,
              Count: secondArea.OffLineCount + secondArea.OnlineCount,
              level: 3,
              onlineCount: secondArea.OnlineCount,
              offLineCount: secondArea.OffLineCount,
              Children: secondArea.School.map(School => ({
                Name: School.SchoolName,
                level: 4,
                Count: School.OffLineCount + School.OnlineCount,
              }))
          }))
        }))
      }
    },
    async GetDictArea(obj){
      const data = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          DeviceName: this.searchform?.DeviceName || '',
          DeviceID: this.searchform?.DeviceID || '',
          DeviceMAC: this.searchform?.DeviceMAC || '',
          Status: 0,
          ...obj
        }
      }
      const res = await connrequest('CenterGetUnknownDevice', data)
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    handleNodeClick(nodeData){
      const {node} = nodeData
      let arr = node.level === 1 ? recursiveGetChildNodePath(node, []) : recursiveGetNodePath(node, [])
      let obj = {}
      if(node.level === 2){
        obj.PrimArea = node.data.Name
      }
      if(node.level === 3){
        obj.SecondArea = node.data.Name
      }
      if(node.level === 4){
        obj.SchoolName = node.data.Name
      }
      this.choseArea = obj
      this.PrimArea = arr
      this.$set(this.Moder, 'PrimArea', arr)
      this.GetDictArea(this.choseArea)
    },
    handleChange(node){
      // console.log(node);
    },
    detailsChange(row){
      this.Action = 4
      this.Moder = {...row, PrimArea: row.PrimArea}
      this.dialogTableVisible = true
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      // if(this.searchform.timeRange){
      //   this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      // }
      this.getData()
    },
    // 重置
    reset(){
      let endTime = new Date()
      let startTime = endTime.getTime() - 10 * 60 * 1000;
      let arr = [ parseTime(startTime), parseTime(endTime)]
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "查询时间"){
          item.initValue = arr
        }else if(item.label === "状态检测" || item.label === "网络应用"){
          item.initValue = 0
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'Status', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    addModer(){
      let arr = [this.nodeData[0].Name, this.nodeData[0].Children[0].Name, this.nodeData[0].Children[0].Children[0].Name, this.nodeData[0].Children[0].Children[0].Name[0].Name] // 赶时间写的，后续需要修改
      this.Action = 1
      this.Moder = {
        SchoolID: getuuid(),
        PrimArea: this.PrimArea || arr
      }
      this.$nextTick(() => {
        this.$refs.Moder.clearValidate();
      })
      this.moderVisible = true
    },
    changeModer(row){
      this.Action = 2
      // this.Moder = {...row, PrimArea:[this.RootName, row.PrimArea, row.SecondArea, row.SchoolName]}
      this.Moder = {
        ...row, 
        PrimArea:[this.RootName, row.PrimArea, row.SecondArea, row.SchoolName], 
        Role: row.Role || this.RoleList?.length > 0 ? this.RoleList[0].Role : '' , 
        StartDate: row.StartDate || Math.round(new Date().getTime())
      }
      this.$nextTick(() => {
        this.$refs.Moder.clearValidate();
      })
      this.moderVisible = true
    },
    deleteModer(row){
      this.$confirm('此操作将永久删除该资产, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data: {
            ...row
          }
        }
        const res = await connrequest('CenterDeleteUnknownDevice', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async submit(){
      this.$refs['Moder'].validate(async (valid) => {
        if (valid) {
          const data = {
            Data: {
              ...this.Moder,
              SchoolID: this.Moder.SchoolID,
              SchoolName: this.Moder.SchoolName,
              DeviceID: this.Moder.DeviceID,
              DeviceName: this.Moder.DeviceName,
              Department: this.Moder.Department,
              DeviceClass: this.Moder.DeviceClass,
              DeviceType: this.Moder.DeviceType,
              ClassName: this.Moder.ClassName,
              UseName: this.Moder.UseName,
              HardID: this.Moder.HardID,
              Phone: this.Moder.Phone,
              Descp: this.Moder.Descp,
              OsInfo: this.Moder.OsInfo,
              ComputerName: this.Moder.ComputerName,
              PrimArea: this.Moder.PrimArea[1],
              SecondArea: this.Moder.PrimArea[2],
              StartDate: Math.round(this.Moder.StartDate / 1000)
            }
          }
          const res = await connrequest('CenterRegDevice', data)
          if(res.Status.StatusCode === 0){
            this.$message.success('注册成功')
            this.moderVisible = false
            this.getData()
          }
        }
      })
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetDictArea(this.choseArea)
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetDictArea(this.choseArea)
    },
    toggleVisibility(isHidden) {
      if(isHidden)
        this.containerWidth = '100%';
      else 
        this.containerWidth = 'calc(100% - 240px)';
    },
  }
};
</script>
<style scoped>
.box {
  background-color: lightblue;
  transition: width 0.5s; /* 添加过渡动画 */
}

</style>
